import DlyAdminLink from '../../model/dlyadminlink'
import DlyAdminUser from '../../model/dlyadminuser'
import DlyAdminShopUser from '../../model/dlyadminshopuser'
import DlyAdminLinkClick from '../../model/dlyadminlinkclick'
import Shop from '../../model/shop'
import Orders from '../../model/orders'

import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
import fs from 'fs'
import path from 'path'
import moment from 'moment'
import { rightsInfo } from '../../api/token'
import redis from '../../dbHelper/redis'
class UserController {
	static async created(ctx) {
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		const createdLinkSave = await new DlyAdminLink({
			adminUserId: jwtuserinfo._id,
			identification:
				(ctx.request.body && ctx.request.body.identification) || '',
		}).save()
		ctx.body = createdLinkSave
	}
	static async list(ctx) {
		const { pageSize = 20, page = 1, status = '', _id = '' } = ctx.query
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		const findFoer = {
			status: status,
			adminUserId:
				jwtuserinfo.roleName === 'adminSp' || jwtuserinfo.roleName === 'admin'
					? ''
					: jwtuserinfo._id,
			_id,
		}
		for (let key in findFoer) {
			if (!findFoer[key]) {
				delete findFoer[key]
			}
		}
		try {
			const getLink = await DlyAdminLink.find(findFoer)
				.populate('adminUserId')
				.limit(pageSize * 1)
				.skip((page - 1) * pageSize)
			const total = await DlyAdminLink.countDocuments(findFoer)
			ctx.body = { list: getLink, total }
		} catch (error) {
			ctx.body = { list: [], total: 0 }
		}
	}
	static async update(ctx) {
		if (
			!ctx.request.body ||
			!ctx.request.body.status ||
			!ctx.params ||
			!ctx.params.id ||
			ctx.params.id.length !== 24
		) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const findData = {
			status: ctx.request.body.status,
		}
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		// adminSp admin 有权限更新所有用户
		const findFoer = {
			_id: ctx.params.id,
			adminUserId:
				jwtuserinfo.role === 'adminSp' || jwtuserinfo.role === 'admin'
					? ''
					: jwtuserinfo._id,
		}
		for (let key in findFoer) {
			if (!findFoer[key]) {
				delete findFoer[key]
			}
		}
		const updataitem = await DlyAdminLink.updateOne(findFoer, findData)

		if (updataitem.nModified === 0) {
			throw new ApiError(ApiErrorNames.NoData)
		}
		ctx.body = 'ok'
	}
	static async deleted(ctx) {
		// 删除链接
		if (!ctx.params || !ctx.params.id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const jwtuserinfo = ctx.request.header.jwtuserinfo
		// adminSp admin 有权限删除所有用户
		const findFoer = {
			_id: ctx.params.id,
			adminUserId:
				jwtuserinfo.role === 'adminSp' || jwtuserinfo.role === 'admin'
					? ''
					: jwtuserinfo._id,
		}
		for (let key in findFoer) {
			if (!findFoer[key]) {
				delete findFoer[key]
			}
		}
		const deleteData = await DlyAdminLink.deleteOne(findFoer)

		if (deleteData.deletedCount === 0) {
			throw new ApiError(ApiErrorNames.NoData)
		}
		ctx.body = 'ok'
	}
	static async binduser(ctx) {
		if (!ctx.params || !ctx.params.id) {
			ctx.redirect(process.env.BUY_URL)
			return
		}
		try {
			const getData = await DlyAdminLink.findOne({ _id: ctx.params.id })
			console.log('代理分享链接')
			if (!getData) {
				ctx.redirect(process.env.BUY_URL)
				return
			}
			console.log('代理分享链接')
			// 返回html文件
			const html = fs.readFileSync(
				path.join(__dirname, '../../views/binduser/index.html'),
				'UTF-8'
			)
			ctx.cookies.set('linkID', ctx.params.id, { httpOnly: false })
			ctx.cookies.set('proxyID', getData.adminUserId, { httpOnly: false })
			ctx.cookies.set('buyUrl', process.env.BUY_URL, { httpOnly: false })
			ctx.body = html
		} catch (error) {
			ctx.redirect(process.env.BUY_URL)
		}
		// 查找id
	}
	static async saveUserProxy(ctx) {
		// 获取请求的外围ip

		try {
			const { uuId, proxyId, linkId } = JSON.parse(ctx.request.body)
			console.log(uuId, proxyId)
			if (!uuId || !proxyId) {
				throw new ApiError(ApiErrorNames.NoParamsData)
			}
			if (linkId) {
				// 累加点击次数
				await DlyAdminLink.updateOne(
					{ _id: linkId },
					{ $inc: { clicks: 1 } }
				)
			}

			const getProxyUser = await DlyAdminUser.findOne({ _id: proxyId })

			let getShopUser = await DlyAdminShopUser.findOne({ uuId })
			// console.log('已经匹配代理与设备关系==》〉设备', getShopUser)
			// console.log('已经匹配代理与设备关系==代理', getProxyUser)
			const currentDate = moment() // 获取当前时间

			const nextWeek = moment(currentDate).add(7, 'days')

			if (!getShopUser) {
				getShopUser = await new DlyAdminShopUser({
					uuId,
					proxyId,
					linkId,
					proxyName: getProxyUser.userName || '',
					proxyExpires: nextWeek.format('YYYY-MM-DD HH:mm:ss'),
				}).save()
			} else {
				getShopUser.proxyId = proxyId
				getShopUser.proxyName = getProxyUser.userName || ''
				getShopUser.proxyExpires = nextWeek.format('YYYY-MM-DD HH:mm:ss')
				getShopUser.linkId = linkId
				getShopUser.save()
			}
			await DlyAdminLinkClick({
				uuId,
				linkId,
				proxyId,
				uuUser: getShopUser._id,
				createdAt: moment().format('YYYY-MM-DD HH:mm:ss')
			}).save()

			ctx.body = 'ok'
			// ctx.redirect(process.env.BUY_URL)
		} catch (error) {
			throw new ApiError(ApiErrorNames.UnknownError)
		}
	}
	static async cheackUserProxy(ctx) {
		// 在这里绑定代理关系
		// console.log('保存用户唯一id：匹配代理信息', ctx.query)
		ctx.verifyParams({
			shopId: { type: 'string', required: true },
			uuId: { type: 'string', required: true },
		})
		const { shopId, uuId, channelCode } = ctx.query

		try {

			// console.log('channelCode', channelCode)
			// if(channelCode) {}
			// 先判断店铺是否存在代理 存在则跳过
			const userShopData = await Shop.findOne({ shop_id: shopId })
			let channelCodeUser
			if (channelCode) {
				channelCodeUser = await DlyAdminUser.findOne({ channelCode })
			}
			const getProxyUserUid = await DlyAdminShopUser.findOne({ uuId })
			// console.log('channelCodeUser', channelCodeUser)
			// console.log('getProxyUserUid', getProxyUserUid)

			// console.log('userShopData', userShopData)
			if (userShopData && userShopData.proxyId) {
				// 店铺存在代理
				// 检查代理是否还是可用的， 不可用的情况需要释放掉
				const getProxyUser = await DlyAdminUser.findOne({ _id: userShopData.proxyId })
				// console.log('getProxyUser', userShopData)
				if (getProxyUser && getProxyUser.status == 1 && !getProxyUser.deleted) {
					// console.log('已经存在代理' + userShopData.proxyId)
					// 查找订单createdTime时间大于 userShopData.proxyStateTime 时间的所有订单
					const getOrders = await Orders.find({
						shop_id: shopId,
						createTime: {
							$gte: moment(new Date(userShopData.proxyStateTime)).subtract(1, 'days')
						}
					}).sort({ createTime: -1 })
					getOrders.forEach(item => {
						item.proxyId = item.proxyId || userShopData.proxyId
						item.proxyLinkId = item.proxyLinkId || userShopData.proxyLinkId
						item.save()
					});
					ctx.body = {
						code: 0,
						msg: '已经存在代理' + userShopData.proxyId,
					}
					return
				}
				// 被删除的情况
				const getProxyUserParenetId = await DlyAdminUser.findOne({ _id: getProxyUser.parentId })
				if (getProxyUserParenetId && getProxyUserParenetId.status == 1 && !getProxyUserParenetId.deleted) {
					await Shop.updateOne(
						{ shop_id: shopId },
						{
							$set: {
								proxyId: getProxyUserParenetId._id,
								proxyLinkId: null,
								proxyStateTime: new Date(),
							}
						}
					)
					// console.log('代理是被禁用了，转为上级代理')
					ctx.body = '代理是被禁用了，转为上级代理'
					return
				}
				// 上级也被删除的情况
				await Shop.updateOne(
					{ shop_id: shopId },
					{
						$set: {
							proxyId: channelCodeUser ? channelCodeUser._id : null,
							proxyLinkId: null,
							proxyStateTime: new Date(),
							channelCode
						}
					}
				)
				// console.log('代理已过期，已经释放')
				ctx.body = '代理已过期，已经释放'
				return
			}
			// 检查浏览器指纹是否存在代理分享

			if (getProxyUserUid) {
				// console.log('getProxyUser', getProxyUser)
				const now = moment()
				// 检查首次记录该浏览器指纹是否超过七天
				if (now.isAfter(getProxyUserUid.proxyExpires)) {
					// 超过七天不做绑定 返回结果
					// console.log('该代理分享链接已经超过七天', channelCodeUser)
					if (channelCode && channelCodeUser) {

						await Shop.updateOne(
							{ shop_id: shopId },
							{
								$set: {
									proxyId: channelCodeUser._id,
									proxyLinkId: null,
									channelCode: channelCode || null
								}
							}
						)
						ctx.body = {
							code: 0,
							msg: '绑定渠道',
						}
						return
					}
					ctx.body = {
						code: 0,
						msg: '该代理分享链接已经超过七天',
					}
					return
				}
				// 最后一个管理的代理关联未超过七天

				if (userShopData.isBuy !== 1) {
					// 未订购状态就需要绑定
					// console.log('getProxyUserAS', getProxyUser)
					console.log('用户未订购，绑定成功')
					await Shop.updateOne(
						{ shop_id: shopId },
						{
							$set: {
								proxyId: getProxyUserUid.proxyId,
								proxyLinkId: getProxyUserUid.linkId,
								proxyStateTime: new Date(),
							}
						}
					)
					// 这里绑定订单关系

					ctx.body = '用户未订购，绑定成功'
					return
				}
				console.log('修改绑定的状态', userShopData)
				// const access_token = ctx.headers.access_token
				const shop_reghts_key = `shop_reghts_${userShopData.shop_id}`
				let rightsInfoData = await redis.get(shop_reghts_key)

				// console.log('getredisshopreghtsdata', rightsInfoData)
				rightsInfoData && (rightsInfoData = JSON.parse(rightsInfoData))
				if (!rightsInfoData) {
					rightsInfoData = await rightsInfo({
						access_token: userShopData.access_token
					})
					redis.set(shop_reghts_key, JSON.stringify(rightsInfoData))
					await redis.expire(shop_reghts_key, 5 * 60)
				}
				// console.log('rightsInfoData', rightsInfoData)

				// console.log('rightsInfoData', rightsInfoData)
				if (rightsInfoData.code === 10000) {
					// console.log('开始的时间', rightsInfoData.data.expire_time)
					// 判断时间是否超过3天
					if (moment(rightsInfoData.data.expire_time).isAfter(moment().add(3, 'days'))) {
						// console.log('用户订购已经超过3天 无法完成绑定')
						ctx.body = '用户订购已经超过3天 无法完成绑定'
						return
					}
					// console.log('需要绑定')
					await Shop.updateOne(
						{ shop_id: shopId },
						{
							$set: {
								proxyId: getProxyUserUid.proxyId,
								proxyLinkId: getProxyUserUid.linkId,
								proxyStateTime: new Date(),
							}
						}
					)
					ctx.body = '已订购用户，在时间内，绑定成功'
					return
				}
				ctx.body = '用户还在订购期内不需要绑定'
			} else {
				// console.log('该设备不存在代理分享记录，收为自有')
				if (channelCode && channelCodeUser) {
					await Shop.updateOne(
						{ shop_id: shopId },
						{
							$set: {
								proxyId: channelCodeUser._id,
								proxyLinkId: null,
								channelCode: channelCode || null
							}
						}
					)
					ctx.body = {
						code: 0,
						msg: '绑定渠道-空代理',
					}
					return
				}
				ctx.body = `${uuId}该设备不存在代理分享记录`

			}

			// 这里绑定订单关系

		} catch (error) {
			console.log('error', error)
			ctx.body = 'error'
		}
		// ctx.body = 'ok'
	}
}

export default UserController
